package breadbox.client.operations;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import breadbox.dataManagement.RMIMessage;
import breadbox.pastry.Message;

/**
 * Code necessary for executing a Get operation
 * @author Forrest
 *
 */
public class Get extends Operation {
	private long[] ids = null;
	private RMIMessage rmiServer;

	/**
	 * Sets up for a Get operation
	 * @param f String filename
	 */
	public Get(long[] ids, RMIMessage server) {
		// check local log for file, fail early if not found
		this.ids = ids;
		this.rmiServer = server;
	}
	
	/**
	 * Sends messages requesting chunks for a file
	 * @return List<Message> sent messages (for debugging)
	 */
	public List<Message> send() {
		List<Message> messages = new ArrayList<Message>();
		for (long id : ids) {
			Message sent = sendMessage(id);
			messages.add(sent);
		}
		return messages;
	}
	
	/**
	 * Sends a message with the given id via RMI
	 * @param id Id of file chunk to request
	 * @return Message contents of message sent (for debugging)
	 */
	private Message sendMessage(long id) {
		Message m = new Message(id, OperationType.GET.toString(), null);
		
		try {
			this.rmiServer.sendMessage(m);
		} catch (RemoteException e) {
			System.err.println("Get error: Cannot send message");
		}
		
		return m;
	}
}
